package cc.admin.modules.bi.util;

import cc.admin.modules.bi.model.Aggregator;
import cc.admin.modules.bi.model.Field;
import cc.admin.modules.bi.model.Group;
import cc.admin.modules.bi.model.ViewExecuteParam;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;

import java.util.List;
/**
 * @author: ZhangHouYing
 * @date: 2021-09-29 7:54
 */
public class SqlUtil {

	public static final String SQL_TEMPLATE = "templates/sql/sqlTemplate.stg";

	public static String renderSql(String sql, ViewExecuteParam executeParam) {
		STGroup stg = new STGroupFile(SQL_TEMPLATE);
		ST st = stg.getInstanceOf("querySql");
		st.add("nativeQuery", false);
		List<Aggregator> aggregators = executeParam.getAggregators();
		//只有有聚合函数那么才需要分组
		boolean addGroupBy = false;
		if (aggregators != null) {
			for (int i = 0; i < aggregators.size(); i++) {
				Aggregator aggregator = aggregators.get(i);
				if (StrUtil.isNotEmpty(aggregator.getFunc())) {
					addGroupBy = true;
					break;
				}
			}
		}
		st.add("addGroupBy", addGroupBy);
		st.add("aggregators", aggregators);
		st.add("groups", executeParam.getGroups());
		st.add("orders", executeParam.getOrders());
		if (StrUtil.isNotEmpty(executeParam.getCnd())) {
			st.add("filters", ImmutableList.of(executeParam.getCnd()));
		}
		st.add("sql", sql);
		st.add("keywordPrefix", "");
		st.add("keywordSuffix", "");
		return st.render();
	}

	public static void main(String[] args) {
		String sql = "select id,name from student";
		ViewExecuteParam executeParam = new ViewExecuteParam();
		List<Group> groupList = Lists.newArrayList();
		Group group = new Group();
		Field field = new Field();
		group.setField(field);
		group.setName("id");
		groupList.add(group);
		executeParam.setGroups(groupList);
		List<Aggregator> aggregatorList = Lists.newArrayList();
		Aggregator aggregator = new Aggregator();
		aggregator.setFunc("");
		aggregator.setColumn("name");
		aggregatorList.add(aggregator);
		executeParam.setAggregators(aggregatorList);
		System.out.println(renderSql(sql, executeParam));
	}
}
